<template>
  <div ref="imgWrapRef" class="cropper-container w-full mx-auto md:w-2/3 xl:w-2/5 relative bg-gray-900">
    <img class="w-full" ref="image" />
    <div class="w-28 h-28 overflow-hidden absolute top-0 right-0" ref="prevRef"></div>
  </div>
</template>
<script>
import { throttle } from "@/utils/utils";
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";

export default {
  name: " JcGePuTouYing",
  props: {
    // eslint-disable-next-line vue/require-prop-type-constructor
    gepuUrl: {
      type: String,
      default: "https://project-star.oss-cn-beijing.aliyuncs.com/assets/32a55dc43e4f2ff9509f5dca16503ea1.jpg",
    },
  },
  emits: ["change"],
  data() {
    return {
      cropper: null,
      loading: false,
      maxHeight: window.innerHeight - 66,
      maxWidth: window.innerWidth,
    };
  },
  mounted() {
    this.init();
  },
  unmounted() {
    this.cropper.destroy();
  },
  methods: {
    init() {
      const image = this.$refs.image;
      if (this.cropper) {
        image.removeEventListener("crop", this.onChange);
        image.removeEventListener("ready", this.onReady);
        this.cropper.destroy();
        this.cropper = null;
      }
      image.src = this.gepuUrl;
      image.alt = "Picture";
      this.cropper = new Cropper(image, {
        viewMode: 0,
        autoCropArea: 0.2 / 1,
        dragMode: "move",
        preview: this.$refs.prevRef,
      });

      image.addEventListener("ready", this.onReady);
      image.addEventListener("crop", this.onChange);
    },
    onReady() {
      const { naturalHeight } = this.cropper.getCanvasData();
      console.log("naturalHeight:", naturalHeight);
      setTimeout(() => {
        this.cropper.setCropBoxData({
          left: 0,
          top: 0,
          width: this.maxWidth,
          height: Math.min(this.maxHeight, naturalHeight),
        });
      }, 300);
    },
    onChange: throttle(function (event) {
      const imgData = this.cropper.getImageData();
      const data = event.detail;
      this.$emit("change", { imgData, data });
    }, 100),
  },
  watch: {
    gepuUrl: function () {
      this.init();
    },
  },
};
</script>
<style scoped lang="less"></style>
